package com.example.gss.controller;

import com.example.gss.entity.Tutor;
import com.example.gss.Service.TutorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/tutors")
public class TutorController {

    @Autowired
    private TutorService tutorService;

    // 创建导师
    @PostMapping
    public ResponseEntity<Tutor> createTutor(@RequestBody Tutor tutor) {
        Tutor createdTutor = tutorService.createTutor(tutor);
        return new ResponseEntity<>(createdTutor, HttpStatus.CREATED);
    }

    // 获取所有导师
    @GetMapping
    public ResponseEntity<List<Tutor>> getAllTutors() {
        List<Tutor> tutors = tutorService.getAllTutors();
        return new ResponseEntity<>(tutors, HttpStatus.OK);
    }

    // 根据ID获取导师
    @GetMapping("/{tutorId}")
    public ResponseEntity<Tutor> getTutorById(@PathVariable String tutorId) {
        Optional<Tutor> tutorOptional = tutorService.getTutorById(tutorId);
        return tutorOptional.map(tutor -> new ResponseEntity<>(tutor, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    // 更新导师
    @PutMapping("/{tutorId}")
    public ResponseEntity<Tutor> updateTutor(@PathVariable String tutorId, @RequestBody Tutor tutor) {
        // 确保更新的是对应ID的导师
        tutor.setTutorId(tutorId);
        Tutor updatedTutor = tutorService.updateTutor(tutor);
        return new ResponseEntity<>(updatedTutor, HttpStatus.OK);
    }

    // 删除导师
    @DeleteMapping("/{tutorId}")
    public ResponseEntity<Void> deleteTutor(@PathVariable String tutorId) {
        tutorService.deleteTutor(tutorId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    // 根据姓名查询导师
    @GetMapping("/search/name")
    public ResponseEntity<List<Tutor>> findTutorsByName(@RequestParam String name) {
        List<Tutor> tutors = tutorService.findTutorsByName(name);
        return new ResponseEntity<>(tutors, HttpStatus.OK);
    }

    // 根据导师组ID查询导师
    @GetMapping("/search/group")
    public ResponseEntity<List<Tutor>> findTutorsByGroupId(@RequestParam String groupId) {
        List<Tutor> tutors = tutorService.findTutorsByGroupId(groupId);
        return new ResponseEntity<>(tutors, HttpStatus.OK);
    }
}